<template>
	<view class="registerClient">
		<text class="title request">您的姓名</text>
		<view class="inp">
			<van-field v-model="info.name" name="pattern" placeholder="请输入名字" :error-message="error.name" />
		</view>


		<text class="title request">性别</text>
		<view class="genderCheckBox">
			<van-radio-group v-model="info.sex" direction="horizontal" >
				<van-radio name="男">男</van-radio>
				<van-radio name="女">女</van-radio>
			</van-radio-group>
			<view class="error-message" v-if="error.sex">
				{{error.sex}}
			</view>
		</view>
		
		
		
		<text class="title request">出生日期</text>
		<view class="selectVant none">
			<uni-datetime-picker
			 type="date"
			  name="birthday"
			   v-model="info.birthday"
				@change="handleDateChange"
				 :max-date="maxDate" />
				 <view class="error-message" v-if="error.birthday">
				 	{{error.birthday}}
				 </view>
		</view>
		
		<!-- <text class="title request">所属行业</text>
		<view class="selectVant" @click="pickerShow('hangye')">
			<van-field readonly clickable name="zpyx" v-model="info.hangye" placeholder="请选择"
				:error-message="error.hangye"  :right-icon="imgUrl + 'under.png'"/>
		</view> -->
		
		<!-- <text class="title request">求职意向</text>
		<view class="selectVant" @click="pickerShow('gangwei')">
			<van-field readonly clickable name="zpyx" v-model="info.gangwei" placeholder="请选择"
				:error-message="error.gangwei"  :right-icon="imgUrl + 'under.png'"/>
		</view> -->

		<text class="title request">您的学历</text>
		<view class="selectVant" @click="pickerShow('education')">
			<van-field readonly clickable name="zpyx" v-model="info.education" placeholder="请选择您的学历"
			  :error-message="error.education"  :right-icon="imgUrl + 'under.png'"/>
		</view>

		<text class="title request">您的学校</text>
		<view class="inp">
			<van-field v-model="info.school" name="pattern" placeholder="请输入您的学校" :error-message="error.school" />
		</view>

		<text class="title request">您的专业</text>
		<view class="inp">
			<van-field v-model="info.major" name="pattern" placeholder="请输入您的专业" :error-message="error.major" />
		</view>
		
		<text class="title request">工作经验</text>
		<view class="selectVant" @click="pickerShow('workExperience')">
			<van-field readonly clickable name="zpyx" v-model="info.workExperience" placeholder="请选择您的工作经验"
			  :error-message="error.workExperience"   :right-icon="imgUrl + 'under.png'" />
		</view>
		
		<text class="title request">所在城市</text>
		<view class="selectVant mb10" @click="pickerShow('area')">
			<van-field readonly clickable name="area" v-model="info.city" placeholder="点击选择省市区"
				:error-message="error.city" :right-icon="imgUrl + 'under.png'" />
		</view>


		<text class="title request">手机号（登录账号）</text>
		<view class="inp mb10">
			<van-field v-model="info.tel" type="number" name="pattern" placeholder="请填写手机号" :error-message="error.tel" />
		</view>

		<view class="inpBox">
			<view class="inp mb10">
				<van-field v-model="graphicsCodeVal" center clearable placeholder="请输入图形验证码" :error-message="error.tcode" />
			</view>
			<view class="graphicsCodeBox" @click="updateGraphicsCode">
				<canvas canvas-id="graphicsCodeCanvas" id="graphicsCodeCanvas" v-if="!src"></canvas>
				<image :src="src" mode="" class="graphicsCodeCanvas" v-else></image>
			</view>
		</view>

		<view class="inpBox">
			<view class="inp">
				<van-field v-model="info.code" name="pattern" type="number" placeholder="请输入验证码"
					:error-message="error.code" />
			</view>
			<view class="getCodeBox">
				<view class="btn" :class="{'disabled':isSend}" @click="sendCode">{{sendTitle || '获取验证码'}}</view>
			</view>
		</view>

		<view class="formItem">
			<button class="submit" @click="submit">确认提交</button>
		</view>

		<!-- 地址Select -->
		<van-popup position="bottom" :show="areaShowPicker">
			<van-area :areaList="areaList" @confirm="selectQydz" @cancel="onCelcel('area')" />
		</van-popup>
		<!-- 公共Select -->
		<picker-view ref="pickerRef" :list="columns" @confirm="onConfirm"></picker-view>
	</view>
</template>

<script>
	import {
		Mcaptcha
	} from '@/utils/mcaptcha'
	import {
		qiuzhiRegister,
		sendCodeFunc
	} from "@/core/web-api/login.js"
	import {
		mapState
	} from "vuex";
	import {
		areaList
	} from '@/node_k/area-data/areadata.js';
	import PickerView from "@/components/PickerView.vue";
	import {validateFunc} from "@/utils/util.js"
	import {getData} from "@/core/web-api/common.js"
	export default {
		components:{
			PickerView
		},
		props:{
			openid:{
				type:String,
				default(){
					return ""
				}
			}
		},
		data() {
			return {
				info: {
					birthday: "",
					code: "",
					education: "",
					major: "",
					name: "",
					school: "",
					sex: "",
					tel: "",
					openid:"",
					gangwei:"",
					hangye:"",
					city:"",
					province:"",
					workExperience:"",
				},
				time: 59, 
				maxDate: new Date().toISOString().split('T')[0], // 获取今天的日期并格式化为 YYYY-MM-DD
				ifBirthdayOk:false,
				timer: null,
				sendTitle: "",
				isSend: false,
				error: {
					code: "",
					education: "",
					major: "",
					name: "",
					school: "",
					sex: "",
					tel: "",
					gangwei:"",
					hangye:"",
					tcode:"",
					city:"",
					province:"",
					workExperience:"",
				},
				mcaptcha:null,
				graphicsCodeVal:"",
				optionsMap:{
					gangweiColumns:[],
					hangyeColumns:[],
					educationColumns:[],
					workExperienceColumns:[],
				},
				type:"",
				columns:[],
				src:"",
				areaList: areaList,
				areaShowPicker: false,
			}
		},
		onReady() {
			this.mcaptcha = new Mcaptcha({
				el: 'graphicsCodeCanvas',
				width: 80,
				height: 35,
				createCodeImg: "",
				instance: this
			});
			this.canvasToImage();
		},
		computed: {
			...mapState(['imgUrl'])
		},
		methods: {
			
			 handleDateChange(newDate) {
			   
				  const selectedDate = new Date(newDate);
				       const today = new Date();
				       const age = today.getFullYear() - selectedDate.getFullYear();
				       const monthDiff = today.getMonth() - selectedDate.getMonth();
				 
				       if (age < 16 || (age === 16 && monthDiff < 0)) {
						   uni.showToast({
						   	title:  "您未满16岁，请重新选择日期",
						    icon: "none"
						   })
						 this.info.birthday = ''; // 清空日期
						 this.ifBirthdayOk=false;
				       }  else{
						   this.ifBirthdayOk=true;
					   }
					   
			   },
			/**
			 * 发送验证码
			 */
			sendCode() {
				console.log(this.info.tel)
				let code = validateFunc(this.info.tel, 'tel')
				if (code != 2) {
					uni.showToast({
						title: code == 0 ? "请输入手机号码" : "手机号码格式错误",
						icon: "none"
					})
					return;
				}
				let grapValid = this.grapValid();
				if (!grapValid) return;
				if (this.isSend) return;
				this.isSend = true;
				this.sendTitle = `${this.time}秒后重发`
				this.sendTel();
				this.timer = setInterval(() => {
					this.time--;
					this.sendTitle = `${this.time}秒后重发`
					if (this.time == 0) {
						clearInterval(this.timer);
						this.time = 60;
						this.isSend = false;
						this.sendTitle = "";
					}
				}, 1000)
			},
			/**
			 * 发送手机号验证码
			 */
			sendTel() {
				sendCodeFunc({
					phone: this.info.tel,
					type: "reg"
				}).then(res => {
					if (res.code == 20000) {
						uni.showToast({
							title: "发送成功"
						})
					}
				})
			},
			/**
			 * 弹出弹窗
			 * @param {Object} type
			 */
			pickerShow(type) {
				this.type = type;
				if (type != 'area') {
					this.columns = this.optionsMap[type + "Columns"];
				}else{
					this.areaShowPicker = true;
					return;
				}
				if (type == 'gangwei') {
					if (!this.optionsMap.gangweiColumns || this.optionsMap.gangweiColumns.length == 0) {
						uni.showToast({
							title: "请选择岗位类别",
							icon: "none"
						})
						return;
					}
					this.$refs.pickerRef.open();
				} else{
					this.$refs.pickerRef.open();
				}
			},
			onConfirm() {
				let value = this.$refs.pickerRef.value;
				if (this.type == 'hangye') {
					this.info.hangye = value;
					let index = this.optionsMap.hangyeColumns.findIndex(f => f.sort == value);
					this.optionsMap.gangweiColumns = this.optionsMap.hangyeColumns[index].datasetTreeVos;
				}
				this.info[this.type] = value
			},
			onCelcel(type) { 
				this.areaShowPicker = false;			 
			},
			/**
			 * 切换图形验证码
			 */
			updateGraphicsCode() {
				this.src = "";
				this.mcaptcha.refresh()
				this.canvasToImage();
			},
			/**
			 * 验证码验证
			 */
			grapValid() {
				if (!this.graphicsCodeVal) {
					uni.showToast({
						title: '请输入图形验证码',
						icon: "none"
					})
					return false;
				}
				if (this.graphicsCodeVal.toLowerCase() != this.mcaptcha.options.createCodeImg.toLowerCase()) {
					uni.showToast({
						title: '图形验证码错误',
						icon: "none"
					})
					return false;
				}
				return true;
			},
			/**
			 * 选择地址
			 */
			selectQydz({
				values
			}) {
				this.info.city = values
					.filter((item) => !!item)
					.map((item) => item.name)
					.join('/');
				this.info.province = this.info.city?this.info.city.split("/")[0]:""
				this.areaShowPicker = false;
			},
			/**
			 * 提交
			 */
			submit() {
				
				let valid = this.validate();
				if (!valid) {
					uni.showToast({
						title: "有必填项未填",
						icon: "none"
					})
					return;
				}
				if (!this.ifBirthdayOk) {
					uni.showToast({
						title: "未满16岁不允许注册",
						icon: "none"
					})
					return;
				}
				let grapValid = this.grapValid();
				if (!grapValid) return;
				const data = JSON.parse(JSON.stringify(this.info));
				qiuzhiRegister(data).then(res => {
					if (res.code == 20000) {
						this.$store.commit("setType",res.data.type);
						this.$store.commit("setToken",res.data.token);
						this.$parent.openRegister(3);
					} else {
						uni.showToast({
							title: res.message,
							icon: "none"
						})
					}
				})
			
			},
			validate() {
				const dist = {
					code: "短信验证码",
					education: "学历",
					birthday: "出生日期",
					major: "专业",
					name: "姓名",
					school: "学校",
					sex: "性别", 
					tel: "手机号",
					city: "所在城市",
					// hangye:"所属行业",
					// gangwei:"求职意向"
				}
				let flag = true;
				for (let key in dist) {
					let code = validateFunc(this.info[key], key);
					if (code == 0) {
						flag = false;
						this.error[key] = dist[key] + "为必填项"
					} else if (code == 1) {
						flag = false;
						this.error[key] = dist[key] + "格式错误"
					} else if (code == 2) {
						this.error[key] = "";
					}
				}
				if(!this.graphicsCodeVal){
					flag = false;
					this.error.tcode = "图形验证码为必填项";
				}else{
					this.error.tcode = "";
				}
				return flag;
			},
			/**
			 * 获取下级筛选
			 */
			getCataList() {
				let cataNames = ['学历', '所属行业','工作经验'];
				let cataList = ['educationColumns','hangyeColumns','workExperienceColumns']
				getData({
					sortList: cataNames
				}).then(res => {
					console.log(res);
					let {
						list
					} = res.data;
					list.forEach(item => {
						let index = cataNames.findIndex(f => f == item.sort);
						this.optionsMap[cataList[index]] = item.list;
					})
					this.optionsMap.educationColumns = this.optionsMap.educationColumns.filter(a=>!a.sort.includes("不限"))
					this.optionsMap.workExperienceColumns = this.optionsMap.workExperienceColumns.filter(a=>!a.sort.includes("不限"))
				})
			},
			getIterative(arrs) {
				let arr = [];
				arrs.forEach(item => {
					arr[item.sort] = item.list.map(f => f.sort);
				})
				return arr;
			},
			canvasToImage(){
				let that = this;
				setTimeout(()=>{
					wx.canvasToTempFilePath({
						canvasId:'graphicsCodeCanvas',
						success:(res)=>{
							this.src = res.tempFilePath
							console.log(res)
						}
					},that)
				},300)
				
			}
		},
		watch:{
			openid:{
				deep:true,
				immediate:true,
				handler(id){
					if(!id) return;
					// this.info.openid = id;
					console.log(id)
				}
			}
		},
		created() {
			console.log(this.maxDate)
			this.getCataList();
		}
	}
</script>

<style scoped lang="less">
	.request{
		position: relative;
		&::after{
			content: '*';
			position: absolute;
			left: -10upx;
			top: 0;
			font-size: 26upx;
			color: #ff0000;
		}
	}
	.registerClient {
		width: 100%;
		background: #fff;
		border-radius: 10px 10px 0px 0px;
		padding: 32px 31px 46px 28px;
		box-sizing: border-box;
	}

	.textareaInp {
		min-height: 60px;
	}

	.title {
		width: 100%;
		font-family: Microsoft YaHei;
		font-weight: 400;
		font-size: 16px;
		color: #000000;
		margin-bottom: 16px;
		padding-left: 5px;
		box-sizing: border-box;
		display: block;
	}

	.inp {
		width: 100%;
		background: #FFFFFF;
		border-radius: 5px;
		border: 1px solid #DCDCDC;
		box-sizing: border-box;
		margin-bottom: 23px;
	}

	.genderCheckBox {
		width: 100%;
		margin-bottom: 23px;
	}

	.selectVant {
		width: 100%;
		background: #FFFFFF;
		border-radius: 5px;
		border: 1px solid #DCDCDC;
		position: relative;
		margin-bottom: 22px;
	}
	.selectVant.none{
		border:0;
	}

	.selectVant::before {
		content: "";
		display: block;
		width: 20px;
		height: 16px;
		background-size: 100% 100%;
		position: absolute;
		top: 50%;
		margin-top: -9px;
		right: 15px;
		z-index: 99;
	}

	.mb10 {
		margin-bottom: 10px !important;
	}

	.inpBox {
		width: 100%;
		position: relative;
	}

	.inpBox canvas {
		width: 100%;
		height: 100%;
	}

	.graphicsCodeBox {
		width: 87px;
		height: 45px;
		box-sizing: border-box;
		position: absolute;
		right: 0;
		top: 0;
		padding: 5px;
		z-index: 9;
		image{
			width: 150upx;
			height: 70upx;
		}
	}

	.getCodeBox {
		position: absolute;
		right: 0;
		top: 0;
		height: 100%;
		padding: 7px 10px 0 0;
		box-sizing: border-box;
		z-index: 10;
	}

	.getCodeBox .btn {
		width: 80px;
		height: 30px;
		line-height: 30px;
		background: #F9F9F9;
		border-radius: 3px;
		border: 1px solid #0180FF;
		text-align: center;
		font-family: Microsoft YaHei;
		font-weight: 400;
		font-size: 12px;
		color: #0180FF;
		
		&.disabled {
			background-color: #f5f5f5;
			border-color: #eee;
			color: #666;
		}
	}

	.submit {
		width: 100%;
		height: 42px;
		line-height: 42px;
		text-align: center;
		background: #0180FF;
		border-radius: 5px;
		font-family: Microsoft YaHei;
		font-weight: 400;
		font-size: 16px;
		color: #FFFFFF;
	}
	.error-message{
		font-size: 24upx;
		color: #ee0a24;
		margin-top: 6upx;
	}
</style>